package com.kaishengit.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.swing.text.html.HTMLDocument.HTMLReader.PreAction;

import com.kaishengit.entity.Order;
import com.kaishengit.entity.User;
import com.kaishengit.util.DBHelp;
import com.kaishengit.util.RowMapper;

public class OrderDao {
	private DBHelp<Order> db = new DBHelp<Order>();
	
	public void save(Order order) {
		String sql = "INSERT INTO t_order (id,address,tel,`name`,createtime,state,userid) VALUES (?,?,?,?,?,?,?)";
		db.executeSQL(sql, order.getId(),order.getAddress(),order.getTel(),order.getName(),order.getCreatetime(),order.getState(),order.getUserid());
	}
	
	public List<Map<String,Object>> findByUserID(int userid) {
		String sql = "SELECT id,createtime,state,(SELECT SUM(total) FROM t_orderitem WHERE orderid = t_order.id) AS sumtotal FROM t_order WHERE userid = ?";
		Connection conn = null;
		PreparedStatement stat = null;
		ResultSet rs = null;
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		try {
			conn = db.getConnection();
			stat = conn.prepareStatement(sql);
			stat.setInt(1, userid);
			rs = stat.executeQuery();
			while(rs.next()) {
				Map<String,Object> map = new HashMap<String, Object>();
				map.put("id", rs.getString("id"));
				map.put("createtime", rs.getString("createtime"));
				map.put("state", rs.getString("state"));
				map.put("sumtotal", rs.getFloat("sumtotal"));
				list.add(map);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			db.close(conn, stat, rs);
		}
		return list;
		
	}
	
	public Order findById(String id) {
		String sql = "SELECT id,address,tel,`name`,createtime,state,userid FROM t_order WHERE id=?";
		return db.executeQueryForObject(sql, new OrderRowMapper(), id);
	}
	
	public List<Order> findByUserId(int userid) {
		String sql= "SELECT id,address,tel,`name`,createtime,state,userid FROM t_order WHERE id=?";
		return db.executeQueryForList(sql, new OrderRowMapper(), userid);
		
	}
	
	private class OrderRowMapper implements RowMapper<Order> {

		public Order mapRow(ResultSet rs) throws SQLException {
			Order order = new Order();
			order.setAddress(rs.getString("address"));
			order.setCreatetime(rs.getString("createtime"));
			order.setId(rs.getString("id"));
			order.setName(rs.getString("name"));
			order.setState(rs.getString("state"));
			order.setTel(rs.getString("tel"));
			order.setUserid(rs.getInt("userid"));
			return order;
		
		}
		
	}
}
